package com.zmc.order.infrastructure.updater.order;

import com.zmc.common.constant.QueueConstant;
import com.zmc.common.exception.base.BusinessException;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.order.infrastructure.bean.vo.OrderReturnApplyVo;
import com.zmc.order.infrastructure.entity.OrderEntity;
import com.zmc.order.infrastructure.entity.OrderReturnApplyEntity;
import com.zmc.order.infrastructure.enums.OrderEnum;
import com.zmc.order.infrastructure.service.MerchantOrderService;
import com.zmc.order.infrastructure.service.OrderReturnApplyService;
import com.zmc.order.infrastructure.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.time.LocalDateTime;

/**
 * @Author：zmc
 * @Date：2025/5/15 18:09
 * 订单申请退款
 */
@Component
public class OrderRefundApplyUpdater<T> implements OderUpdater<T> {

    public static Logger log = LoggerFactory.getLogger(OrderRefundApplyUpdater.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private AuthTokenService authTokenService;

    @Autowired
    private OrderReturnApplyService orderReturnApplyService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public void execute(T param) {
        OrderReturnApplyVo vo = (OrderReturnApplyVo) param;
        String orderNo = vo.getOrderSn();
        OrderEntity order = orderService.getByOrderSn(orderNo);
        if (order == null) {
            throw new BusinessException("当前订单不存在");
        }
        if (order.getStatus() == OrderEnum.ORDER_STATUS_REFUNDING.getCode()) {
            log.warn("当前订单：orderSn:{},正在退款中", order.getOrderSn());
            throw new BusinessException("正在退款中");
        } else if (order.getStatus() == OrderEnum.ORDER_STATUS_REFUNDED.getCode()) {
            log.warn("当前订单：orderSn:{},已完成退款", order.getOrderSn());
            throw new BusinessException("订单已完成退款");
        } else if (order.getStatus() == OrderEnum.ORDER_STATUS_WAIT_SEND_GOOD.getCode() ||
                order.getStatus() == OrderEnum.ORDER_STATUS_HAS_SEND_GOOD.getCode() ||
                order.getStatus() == OrderEnum.ORDER_STATUS_COMPLETE.getCode()) {
            OrderReturnApplyEntity returnApplyEntity = new OrderReturnApplyEntity();
            returnApplyEntity.setMerchantId(order.getMerchantId());
            returnApplyEntity.setOrderSn(order.getOrderSn());
            returnApplyEntity.setCreateTime(LocalDateTime.now());
            returnApplyEntity.setReturnAmount(order.getPayAmount());
            if (order.getStatus() == OrderEnum.ORDER_STATUS_WAIT_SEND_GOOD.getCode()) {
                returnApplyEntity.setStatus(OrderEnum.ORDER_REFUND_PROCESSING.getCode());
            } else {
                returnApplyEntity.setStatus(OrderEnum.ORDER_REFUND_PENDING.getCode());
            }
            returnApplyEntity.setDescription(vo.getDescription());
            returnApplyEntity.setDescPics(vo.getDescPics());
            returnApplyEntity.setReason(vo.getReason());
            returnApplyEntity.setMemberUsername(authTokenService.getMemberInfo().getAccount());
            orderReturnApplyService.save(returnApplyEntity);
            orderService.updateStatus(orderNo, OrderEnum.ORDER_STATUS_REFUNDING.getCode());
            merchantOrderService.updateStatus(order.getMerchantOrderSn(), OrderEnum.ORDER_STATUS_REFUNDING.getCode());
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    //若订单是未发货状态，立即退款
                    if (returnApplyEntity.getStatus() == OrderEnum.ORDER_REFUND_PROCESSING.getCode()) {
                        rabbitTemplate.convertAndSend(QueueConstant.REFUND_EXCHANGE, QueueConstant.REFUND_ROUTING_KEY, order.getOrderSn());
                    }
                }
            });
        } else {
            log.error("当前订单：orderSn:{}, status: {}, 不能退款", order.getOrderSn(), order.getStatus());
            throw new BusinessException("当前订单状态不能退款");
        }
    }
}
